package com.oa.utils;

import com.mdp.core.utils.DateUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.servlet.view.document.AbstractXlsxView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* 将数据加载到EXCEL中输出到页面
* @author cyc 
* @version 1.0
 */
public class ExcelView extends AbstractXlsxView{

		@Override
	protected void buildExcelDocument(Map<String, Object> model,
			Workbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
				Date date = new Date();
				String filename = DateUtils.format(date, "yyyyMMddHHmmss");
				Sheet sheet;
				Cell cell;
				response.setContentType("application/vnd.ms-excel");  
				response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");
				
				sheet = workbook.createSheet("sheet1");
				
				List<String> titles = (List<String>) model.get("titles");
				int len = titles.size();
				CellStyle headerStyle = workbook.createCellStyle(); //标题样式
				headerStyle.setAlignment(HorizontalAlignment.CENTER);
				headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
				Font headerFont = workbook.createFont();	//标题字体
				headerFont.setBold(true);
				headerFont.setFontHeightInPoints((short)11);
				headerStyle.setFont(headerFont);
				short width = 20,height=25*20;
				sheet.setDefaultColumnWidth(width);
				Row row0=sheet.createRow(0);
				for(int i=0; i<len; i++){ //设置标题
					String title = titles.get(i);
					cell=row0.createCell(i);
					cell.setCellStyle(headerStyle);
					cell.setCellValue(title);
				}
				row0.setHeight(height);
				
				CellStyle contentStyle = workbook.createCellStyle(); //内容样式
				contentStyle.setAlignment(HorizontalAlignment.CENTER);
				List<Map<String,Object>> varList = (List<Map<String,Object>>) model.get("varList");
				int varCount = varList.size();
				for(int i=0; i<varCount; i++){
					Row row=sheet.createRow(i+1);
					Map<String,Object> vpd = varList.get(i);
					for(int j=0;j<len;j++){
						Object value=vpd.get("var"+(j+1));
						cell = row.createCell(j);
						cell.setCellStyle(contentStyle);
						if(value==null){
							cell.setCellValue("");
						}else if(value instanceof Date){
							cell.setCellValue((Date)value);
						}else if(value instanceof Boolean){
							cell.setCellValue((Boolean)value);
						}else if(value instanceof Integer){
							cell.setCellValue((Integer)value);
						}else if(value instanceof Double){
							cell.setCellValue((Double)value);
						}else if(value instanceof Float){
							cell.setCellValue((Float)value);
						}else{
							cell.setCellValue((String)value);
						}
						
					}
					
				}
		
	}

}
